<?php
/**
 * Created by PhpStorm.
 * User: suncco
 * Date: 2018/6/25
 * Time: 17:38
 *
 * d:上传模块
 */

namespace app\code\controller;


use think\Controller;

class upload extends Controller
{
    public function index(){

        return view();
    }

    public function upload(){
//        dump($_FILES);die;
        $Path = null;
        if ($_FILES['img']['name']) {
            $Img = $this->saveimg($_FILES);
            dump($Img);die;
        }else{
            echo '请选择图片';
        }
    }

    public function saveimg(){
        $mimes = array(
            'image/jpeg',
            'image/jpg',
            'image/jpeg',
            'image/png',
            'image/pjpeg',
            'image/gif',
            'image/bmp',
            'image/x-png'
        );
        $exts = array(
            'jpeg',
            'jpg',
            'jpeg',
            'png',
            'pjpeg',
            'gif',
            'bmp',
            'x-png'
        );

        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('img');

        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){
//            $info = $file->move('attached');
            $info = $file->rule('date')->validate(['size'=>1048576,'ext'=>$exts])->move( '../application/code/attached');
            if($info){
                $filePath = '/attached/'.$info->getSaveName();//输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                //$filePath = '/attached/'.$info->getExtension();// 输出 jpg
                //$filePath = '/attached/'.$info->getFilename();// 输出 42a79759f284b767dfcb2a0197904287.jpg
            }else{
                // 上传失败获取错误信息
                $error = $file->getError();
                echo "<script>alert('{$error}')</script>";
            }
        }
        $ImgStr = $filePath;
        return $ImgStr;
    }

    public function uploads(){
        $mimes = array(
            'image/jpeg',
            'image/jpg',
            'image/jpeg',
            'image/png',
            'image/pjpeg',
            'image/gif',
            'image/bmp',
            'image/x-png'
        );
        $exts = array(
            'jpeg',
            'jpg',
            'jpeg',
            'png',
            'pjpeg',
            'gif',
            'bmp',
            'x-png'
        );
        // 获取表单上传文件
        $files = request()->file('img');
//        dump($files);die;
        foreach($files as $file){
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->rule('date')->validate(['size'=>1048576,'ext'=>$exts])->move( '../application/code/attached');
            if($info){
                // 成功上传后 获取上传信息
                // 输出 jpg
                echo $info->getExtension();
                // 输出 42a79759f284b767dfcb2a0197904287.jpg
                echo $info->getFilename();
            }else{
                // 上传失败获取错误信息
                echo $file->getError();
            }
        }
    }
}